import re

from django.contrib.auth.hashers import make_password
from django_redis import get_redis_connection
from rest_framework import serializers
from saas_main import models
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueTogetherValidator
from django.conf import settings


class MobileSerializer(serializers.Serializer):
    mobile = serializers.CharField(validators=[])

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise ValidationError('手机号格式错误')
        return value


class UserSerializer(serializers.ModelSerializer):
    confirm_password = serializers.CharField(write_only=True)
    code = serializers.CharField(write_only=True)
    mobile = serializers.CharField()

    class Meta:
        model = models.User
        fields = ["username", "password", "confirm_password", "realname", "email", "mobile", "code"]
        extra_kwargs = {
            "password": {"write_only": True},

        }

    def validate_password(self, value):
        return make_password(value, salt=settings.PWD_SALT)

    def validate_confirm_password(self, value):
        return make_password(value, salt=settings.PWD_SALT)

    def validate(self, attrs):
        if attrs.get('password') != attrs.get('confirm_password'):
            raise ValidationError('两次输入的密码不一致')
        conn = get_redis_connection()
        redis_code = conn.get(attrs.get('mobile'))
        if not redis_code:
            raise ValidationError('验证码已失效或者未发送，请重新发送')
        if attrs.get('code') != redis_code.decode('utf-8').strip():
            raise ValidationError('验证码输入错误')
        attrs.pop('confirm_password')
        attrs.pop('code')
        return attrs


class LoginSerializer(serializers.Serializer):
    account = serializers.CharField()
    password = serializers.CharField()
    code = serializers.CharField()

    def validate_code(self, value):
        if value == self.context['session'].get('image_code'):
            return value
        raise ValidationError("验证码输入错误")

    def validate(self, attrs):
        account = attrs.get("account")
        if re.match(r'^1[3-9]\d{9}$', account):
            user = models.User.objects.filter(mobile=account).first()
        elif re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$', account):
            user = models.User.objects.filter(email=account).first()
        else:
            user = models.User.objects.filter(username=account).first()
        if user:
            attrs.update({"user": user})
            return attrs
        else:
            raise ValidationError("用户不存在！")


class UserRightSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.UserRight
        fields = '__all__'


class PaymentSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.RightOrder
        fields = '__all__'

    def validate(self, attrs):
        price = attrs['order_right'].price
        if price * attrs['order_quantity'] != attrs["order_price"]:
            raise ValidationError('订单价格错误，请刷新页面重新下单')
        return attrs
